//获取应用实例
const app = getApp();
// 引入AES.js
var baseJs = require("../../common/base.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: baseJs.imgUrl,
    goodsData: [],
    orderInfo: "",
    buyNum: 0,
    buyType: 0,
    endMoney: 0,
    youFei: 0.00,
    // 默认收货地址
    defaultAddress: [],
    // 弹出选择收货地址
    chooseFlag: false,
    addressData: [],
    // 新增地址
    addFlag: true,
    color: "#808080",
    region: ['', '', ''],
    // 去付款
    payFlag: true,
    // 余额/微信
    payType: '',
    // 买家留言
    leaveMessage: "",
    createOrderData: [],
    // 
    isArea: "",
    isBuluoArea: "",
    // 
    uid: "",
    // 优惠券
    ticketFlag: true,
    businessId: "",
    ticketList: [],
    ticketId: 0,
    // 支付详情
    payDetail: "",
    // 输入支付密码
    //是否展示密码输入层
    showPayPwdInput: false,
    //输入的密码
    payPasswords: "",
    //文本框焦点
    payFocus: true,
    // 是否已经设置支付密码
    isAlreadyPayPassword: "",

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options);
    this.setData({
      uid: wx.getStorageSync('uid'),
      isAlreadyPayPassword: wx.getStorageSync('isAlreadyPasswords'),
      goodsId: options.goodsId,
      businessId: options.businessId,
      orderInfo: options.orderInfo,
      isArea: options.isArea,
      isBuluoArea: options.isBuluoArea,

    })
    // var isArea = this.data.isArea;
    // var isBuluoArea = this.data.isBuluoArea;
    // console.log(isArea);
    // console.log(isBuluoArea);
    this.setData({
      buyNum: this.data.orderInfo.split('*')[1],
      buyType: this.data.orderInfo.split('*')[this.data.orderInfo.split('*').length - 1],
    })
    this.GetGoodInfoByID();
    this.GetMyDefaultAddress();

  },

  //显示支付密码输入层
  showInputLayer: function () {
    this.setData({
      showPayPwdInput: true,
      payFocus: true
    });
  },
  //隐藏支付密码输入层
  cancelInputPasswords: function () {
    var val = this.data.payPasswords;
    this.setData({
      showPayPwdInput: false,
      payFocus: false,
      payPasswords: ''
    });

  },
  // 获取焦点
  getFocus: function () {
    this.setData({
      payFocus: true
    });
  },
  //输入密码,监听
  inputPwd: function (e) {
    this.setData({
      payPasswords: e.detail.value
    });
  },
  //输入密码 确定 
  surePasswords: function () {
    var that = this;
    var uid = this.data.uid;
    var payPasswords = this.data.payPasswords;
    var createOrderData = this.data.createOrderData;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=CheckMyTradePassword&UID=" + uid + "&TradePassword=" + payPasswords),
      success: function (res) {
        var json = JSON.parse(baseJs.decryUrl(res.data));
        console.log(json);
        if (json.ResultFlag == 1) {
          wx.request({
            url: baseJs.api + baseJs.encryUrl("method=PayOrder1&SerialNumber=" + createOrderData.OrderNumber + "&PayType=0"),
            success: function (res) {
              var json = JSON.parse(baseJs.decryUrl(res.data))
              console.log(json);
              if (json.ResultFlag == 1) {
                wx.showToast({
                  title: json.ResultMsg,
                  icon: 'none',
                  duration: 2000
                });
                setTimeout(function () {
                  wx.reLaunch({
                    url: '../mine/mine',
                  })
                }, 500)
              } else {
                wx.showToast({
                  title: json.ResultMsg,
                  icon: 'none',
                  duration: 2000
                });
              }
            }
          })
        } else {
          wx.showToast({
            title: json.ResultMsg,
            icon: 'none',
            duration: 2000
          });
        }
      }
    })
  },
  // 获取商品信息
  GetGoodInfoByID: function () {
    var that = this;
    var uid = this.data.uid;
    var goodsId = this.data.goodsId;
    var businessId = this.data.businessId;
    var goodsData = this.data.goodsData;
    var endMoney = this.data.endMoney;
    var orderInfo = this.data.orderInfo;
    var buyNum = this.data.buyNum;
    var youFei = this.data.youFei;
    var buyType = this.data.buyType;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetGoodInfoByID&GID=" + goodsId + "&Uid=" + uid),
      success: function (res) {
        // console.log(JSON.parse(baseJs.decryUrl(res.data)));
        goodsData = JSON.parse(baseJs.decryUrl(res.data)).ResultData;
        endMoney = buyNum * JSON.parse(baseJs.decryUrl(res.data)).ResultData.Price;
        if (buyType == 1) {
          // 兑换
          youFei = 0.00;
        } else {
          youFei = JSON.parse(baseJs.decryUrl(res.data)).ResultData.Youfei
        }
        that.setData({
          goodsData: goodsData,
          endMoney: endMoney,
          youFei: youFei,
        })
        console.log(goodsData);
      }
    })

  },

  // 选择收货地址
  chooseAddressTap0: function () {
    this.GetMyAddress();
    this.setData({
      chooseFlag: !this.data.chooseFlag
    });
  },
  chooseAddressTap1: function () {
    this.setData({
      chooseFlag: !this.data.chooseFlag
    });
  },
  // 获取收货地址
  GetMyAddress: function () {
    var that = this;
    var uid = this.data.uid;
    var addressData = this.data.addressData;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetMyAddress&UID=" + uid),
      success: function (res) {
        console.log("地址" + JSON.parse(baseJs.decryUrl(res.data)));
        addressData = JSON.parse(baseJs.decryUrl(res.data)).ResultData;

        that.setData({
          addressData: addressData,

        })
      }
    })

  },
  // 新增收货地址
  addAddressTap: function () {
    this.setData({
      addFlag: !this.data.addFlag
    });
  },
  // 
  bindRegionChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value,
      color: "#333",
    })
  },
  // 新增地址 提交
  formSubmit: function (e) {
    // console.log('form发生了submit事件，携带数据为：', e.detail.value);
    var that = this;
    var uid = this.data.uid;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=AddAddress&UID=" + uid + "&UserName=" + e.detail.value.name + "&tel=" + e.detail.value.phone + "&Address=" + e.detail.value.area[0] + " " + e.detail.value.area[1] + " " + e.detail.value.area[2] + "&Memo=" + e.detail.value.detailAddress),
      success: function (res) {
        if (JSON.parse(baseJs.decryUrl(res.data)).ResultFlag == 1) {
          wx.showToast({
            title: JSON.parse(baseJs.decryUrl(res.data)).ResultMsg,
            icon: 'none',
            duration: 2000
          });
          setTimeout(function () {
            that.setData({
              addFlag: true,
              chooseFlag: false
            })
          }, 2000)
          that.GetMyDefaultAddress();
        } else {
          wx.showToast({
            title: JSON.parse(baseJs.decryUrl(res.data)).ResultMsg,
            icon: 'none',
            duration: 2000
          });
        }
      }
    })

  },
  // 新增地址 取消
  formReset: function () {
    this.setData({
      addFlag: !this.data.addFlag,
    })
  },
  // 获取默认收货地址
  GetMyDefaultAddress: function () {
    var that = this;
    var uid = this.data.uid;
    var defaultAddress = this.data.defaultAddress;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetMyDefaultAddress&UID=" + uid),
      success: function (res) {
        var json = JSON.parse(baseJs.decryUrl(res.data));
        console.log(JSON.parse(baseJs.decryUrl(res.data)));
        if (json.ResultFlag == 1) {
          defaultAddress = JSON.parse(baseJs.decryUrl(res.data)).ResultData;
          that.setData({
            defaultAddress: defaultAddress,
          })
        } else { }
      }
    })
  },
  // 设置默认地址
  setDefaultAddress: function (e) {
    var that = this;
    var uid = this.data.uid;
    // console.log(e);
    var addressId = e.currentTarget.dataset.addressid;
    // console.log(addressId);
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=UpDefaultAddress&UID=" + uid + "&ID=" + addressId),
      success: function (res) {
        // console.log(JSON.parse(baseJs.decryUrl(res.data)));
        if (JSON.parse(baseJs.decryUrl(res.data)).ResultFlag == 1) {
          that.GetMyDefaultAddress();
          setTimeout(function () {
            that.setData({
              chooseFlag: !that.data.chooseFlag,
            })
          }, 1000)
        } else { }
      }
    })
  },
  // 买家留言
  messageTap: function (e) {
    var leaveMessage = this.data.leaveMessage;
    leaveMessage = e.detail.value;
    this.setData({
      leaveMessage: leaveMessage,
    });
  },
  //余额或微信 
  radioChange: function (e) {
    var payType = this.data.payType;
    payType = e.detail.value
    this.setData({
      payType: payType,
    });
  },
  // 提交订单
  createOrder1: function () {
    this.setData({
      payFlag: !this.data.payFlag,
    });
  },
  // 提交订单
  createOrder0: function () {
    var that = this;
    var uid = this.data.uid;
    var orderInfo = this.data.orderInfo;
    var leaveMessage = this.data.leaveMessage;
    var defaultAddress = this.data.defaultAddress;
    var createOrderData = this.data.createOrderData;
    var isArea = this.data.isArea;
    var isBuluoArea = this.data.isBuluoArea;
    var ticketId = this.data.ticketId;
    var payDetail = this.data.payDetail;
    var payFlag = this.data.payFlag;
    wx.showLoading({
      title: '正在生成订单',
    })
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GenerateOrder1&UID=" + uid + "&remark=" + leaveMessage + "&OrderInfo=" + orderInfo + "&Consignee=" + defaultAddress.UserName + "&ConsigneePhone=" + defaultAddress.tel + "&ConsigneeAddress=" + defaultAddress.Address + "&DiscountId=" + ticketId + "&IsHelpBuy=0&HelpBuyUID=0&BackMaMaxRate=0&BaiduX=&BaiduY=" + "&IsArea=" + isArea + "&IsBuluoArea=" + isBuluoArea),
      // header:{
      //     'content-type':'application/json'
      // },
      success: function (res) {
        console.log(res);
        var json = JSON.parse(baseJs.decryUrl(res.data));
        console.log(json);
        if (json.ResultFlag == 1) {
          wx.hideLoading()
          createOrderData = json.ResultData;
          that.setData({
            createOrderData: createOrderData
          })
          // 判断
          if (parseFloat(json.ResultData.CouponEdu).toFixed(2) > 0 && parseFloat(json.ResultData.useNeedPayMa).toFixed(2) == 0) {
            payDetail = parseFloat(json.ResultData.CouponEdu).toFixed(2) + "M（易易红包抵扣）  +  " + parseFloat(json.ResultData.useNeedBuxianRMB).toFixed(2) + "元(补现)  +  " + parseFloat(json.ResultData.Youfei).toFixed(2) + "元(邮费)";
            that.setData({
              payDetail: payDetail,
            })
          } else if (parseFloat(json.ResultData.CouponEdu).toFixed(2) > 0 && parseFloat(json.ResultData.useNeedPayMa).toFixed(2) > 0) {
            payDetail = parseFloat(json.ResultData.useNeedPayMa).toFixed(2) + "M  +  " + parseFloat(json.ResultData.CouponEdu).toFixed(2) + "M（易易红包抵扣）  +  " + parseFloat(json.ResultData.useNeedBuxianRMB).toFixed(2) + "元(补现)  +  " + parseFloat(json.ResultData.Youfei).toFixed(2) + "元(邮费)";
            that.setData({
              payDetail: payDetail,
            })
          } else {
            payDetail = parseFloat(json.ResultData.useNeedPayMa).toFixed(2) + "M  +  " + parseFloat(json.ResultData.useNeedBuxianRMB).toFixed(2) + "元(补现)  +  " + parseFloat(json.ResultData.useNeedPayMaFee).toFixed(2) + "元(M管理费) + " + parseFloat(json.ResultData.Youfei).toFixed(2) + "元(邮费)";
            that.setData({
              payDetail: payDetail,
            })
          }
          if (parseFloat(json.ResultData.useNeedPayMa).toFixed(2) == 0 || parseFloat(json.ResultData.useNeedBuxianRMB).toFixed(2) > 0) {
            wx.showModal({
              title: '提示',
              content: "您购买该产品需支付全现金交易, 是否继续？",
              success(res) {
                if (res.confirm) {
                  console.log('用户点击确定');
                  that.setData({
                    payFlag: false,
                  });
                } else if (res.cancel) {
                  console.log('用户点击取消');
                }
              }
            })
          }
        } else {
          wx.showToast({
            title: json.ResultMsg,
            icon: 'none',
            duration: 2000
          });
        }

      }
    })
  },
  // 付款
  goPay: function () {
    var that = this;
    var payType = this.data.payType;
    console.log(payType)
    var createOrderData = this.data.createOrderData;
    var isAlreadyPayPassword = this.data.isAlreadyPayPassword;
    if (payType == '') {
      wx.showToast({
        title: "请选择支付方式",
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    this.setData({
      payFlag: true
    })
    if (payType == "0") {
      if (isAlreadyPayPassword == '1') {
        that.setData({
          showPayPwdInput: true,
          payFocus: true,
          payFlag: true
        })
      } else {
        wx.showToast({
          title: "请先去设置支付密码！",
          icon: 'none',
          duration: 2000
        });
      }
    } else {
      wx.request({
        url: baseJs.api + baseJs.encryUrl("method=PayOrder1&SerialNumber=" + createOrderData.OrderNumber + "&PayType=2"),
        success: function (res) {
          var json = JSON.parse(baseJs.decryUrl(res.data));
          console.log(json);
          if (json.ResultFlag == 1) {
            // wx.requestPayment({
            //   timeStamp: json.ResultData.timestamp,
            //   nonceStr: json.ResultData.nonce_str,
            //   package: 'prepay_id=' + json.ResultData.prepay_id,
            //   signType: 'MD5',
            //   paySign: json.ResultData.sign,
            //   success(res) {
            //     console.log(res);
            //     wx.showToast({
            //       title: res.err_desc,
            //       icon: 'none',
            //       duration: 2000
            //     });
            //     setTimeout(function() {
            //       wx.reLaunch({
            //         url: '../mine/mine',
            //       })
            //     }, 500)
            //   },
            //   fail(res) {
            //     console.log(res);
            //     wx.showToast({
            //       title: res.err_desc,
            //       icon: 'none',
            //       duration: 2000
            //     });
            //   }
            // })
          } else {
            wx.showToast({
              title: json.ResultMsg,
              icon: 'none',
              duration: 2000
            });
          }


        }
      })
    }

  },
  // 优惠券
  chooseTicket: function () {
    var that = this;
    var uid = this.data.uid;
    var businessId = this.data.businessId;
    var ticketList = this.data.ticketList;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetCanUseCoupon&UID=" + uid + "&SJID=" + businessId),
      success: function (res) {
        console.log("method=GetCanUseCoupon&UID=" + uid + "&SJID=" + businessId);
        var json = JSON.parse(baseJs.decryUrl(res.data));
        console.log(json);
        if (json.ResultData.length > 0) {
          that.setData({
            ticketList: json.ResultData,
            ticketFlag: false,
          })
        } else {
          wx.showModal({
            title: '提示',
            content: "您没有可使用的易易红包!",
            showCancel: false
          })
        }
      }
    })
  },
  // 
  ticketRadioChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value);
    this.setData({
      ticketId: e.detail.value,
    })
  },
  // 
  ticketConfirm: function () {
    this.setData({
      ticketFlag: true,
    })
  },
  // 
  ticketCancel: function () {
    this.setData({
      ticketFlag: true,
    })
  },
  // 
})